package com.qf.ability.gateway.application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.reactive.ReactorResourceFactory;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @author YaoJiXing
 * created 2022/8/29 15:34
 */
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    @Bean
    public ReactorResourceFactory reactorClientResourceFactory() {
        System.setProperty("reactor.netty.ioSelectCount", "1");

        // 这里工作线程数为2-4倍都可以。看具体情况
        int ioWorkerCount = Math.max(Runtime.getRuntime().availableProcessors() * 3, 4);
        System.setProperty("reactor.netty.ioWorkerCount", String.valueOf(ioWorkerCount));
        return new ReactorResourceFactory();
    }

    /**
     * 设置gateway的跨域过滤器
     * @return
     */
    @Bean
    public CorsWebFilter getCorsWebFilter() {
        //进行跨域的配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许所有类型的方法跨域 GET POST
        corsConfiguration.addAllowedMethod("*");
        //允许任何请求头的请求跨域
        corsConfiguration.addAllowedHeader("*");
        //允许任何请求的主机地址跨域
        corsConfiguration.addAllowedOrigin("*");
        //允许cookie跨域
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsWebFilter(urlBasedCorsConfigurationSource);
    }
}
